package com.yoomiito.app.net;

import android.graphics.Bitmap;
import android.util.Log;

import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.yoomiito.app.model.cicle.QiniuTokenInfo;
import com.yoomiito.app.utils.L;
import com.yoomiito.app.utils.NetworkUtils;
import com.yoomiito.app.utils.YMToast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;

import cn.droidlover.xdroidmvp.net.ApiException;
import cn.droidlover.xdroidmvp.net.ApiSubscriber;
import cn.droidlover.xdroidmvp.net.XApi;

/************************************************************
 * Author:  linqiang
 * Description:     // 模块描述
 * Date: 2019/5/1
 ************************************************************/
public class UploadFileManager {

    public static final int CODE_OBTAIN_TOKEN_FAILED = 0;
    public static final int CODE_UPFILE_FAILED = 1;

    public static class UPManager {
        //        Configuration config = new Configuration.Builder()
//                .zone(Zone.zone0) // 自动识别
//                .build();
//        UploadManager uploadManager = new UploadManager(config);
//        static UploadManager uploadManager = new UploadManager(new Configuration.Builder()
//                .zone(Zone.) // 自动识别
//                .build());
        static UploadManager uploadManager = new UploadManager();
    }

    public static QiniuTokenInfo tokenQiniu;

    public static interface UploadFileCallBack {
        void uploadSucc(String filename, String key);

        void uploadFail(int code, String key);
    }

    public static void uploadFile(Object bitmap, String key, UploadFileCallBack uploadFileCallBack) {
//        if(tokenQiniu == null||tokenQiniu.isTimeOut()){
        obtainAndcheckToken(bitmap, key, uploadFileCallBack);
//        }else {
//            up(bitmap,key,uploadFileCallBack,tokenQiniu);
//        }
    }

    static void up(Object bitmap, final String sign, final UploadFileCallBack uploadFileCallBack, QiniuTokenInfo tokenQiniu) {
        String token = tokenQiniu.getToken();

        if (bitmap instanceof Bitmap) {

            byte[] bytes = bitmap2bytes((Bitmap) bitmap);
            UPManager.uploadManager.put(bytes, null, token,
                    new UpCompletionHandler() {
                        @Override
                        public void complete(String key, ResponseInfo info, JSONObject res) {
                            //res包含hash、key等信息，具体字段取决于上传策略的设置。
                            Log.i("qiniu", key + ",\r\n " + info + ",\r\n " + res);
                            if (info.isOK()) {
                                if (uploadFileCallBack != null) {
                                    try {
                                        String imageUrl = tokenQiniu.getUrl() + "/"+ res.getString("key");
                                        Log.i("qiniu", "imageUrl========================================-->" + imageUrl);
                                        uploadFileCallBack.uploadSucc(imageUrl, sign);
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            } else {
                                if (uploadFileCallBack != null) {
                                    uploadFileCallBack.uploadFail(CODE_UPFILE_FAILED, sign);
                                    UploadFileManager.tokenQiniu = null;
                                }
                            }
                        }
                    }, null);
        } else if (bitmap instanceof String) {
            UPManager.uploadManager.put((String) bitmap, null, token,
                    new UpCompletionHandler() {
                        @Override
                        public void complete(String key, ResponseInfo info, JSONObject res) {
                            L.i("完成");

                            //res包含hash、key等信息，具体字段取决于上传策略的设置。
                            Log.i("qiniu", key + ",\r\n " + info + ",\r\n " + res);
                            if (info.isOK()) {
                                if (uploadFileCallBack != null) {
                                    try {
                                        String imageUrl = tokenQiniu.getUrl() + "/" + res.getString("key");
                                        Log.i("qiniu", "imageUrl========================================-->" + imageUrl);
                                        uploadFileCallBack.uploadSucc(imageUrl, sign);
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            } else {
                                if (uploadFileCallBack != null) {
                                    uploadFileCallBack.uploadFail(CODE_UPFILE_FAILED, sign);
                                    UploadFileManager.tokenQiniu = null;
                                }
                            }
                        }
                    }, null);
        }


    }

    static void obtainAndcheckToken(final Object bitmap, final String key, final UploadFileCallBack uploadFileCallBack) {
        YmApi.getYmService()
                .getQiniuToken()
                .compose(XApi.<QiniuTokenInfo>getApiTransformerData())
                .compose(XApi.<QiniuTokenInfo>getScheduler())
                .subscribe(new ApiSubscriber<QiniuTokenInfo>() {
                    @Override
                    public void onSuccess(QiniuTokenInfo data) {
                        tokenQiniu = data;
                        up(bitmap, key, uploadFileCallBack, tokenQiniu);
                    }

                    @Override
                    public void onFail(ApiException error) {
                        YMToast.showText("error");
                    }
                });
    }

    static byte[] bitmap2bytes(Bitmap bmp) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();//初始化一个流对象
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);//把bitmap100%高质量压缩 到 output对象里

        bmp.recycle();//自由选择是否进行回收

        byte[] result = output.toByteArray();//转换成功了
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}
